/**
 * Copyright 2024 The coretext Authors. All Rights Reserved.
 */
import { Block } from './block/Block';
import { BlockProvider } from './builder/BlockProvider';
import { NumberUtils } from './utils/NumberUtils';
import { TextUtils } from './utils/TextUtils';

export class AttributedString {

  private text: string;
  private separator: string;
  private blockSections: Array<BlockSection>;

  constructor(text: string, separator: string = "") {
    this.text = text;
    this.separator = separator;
  }

  public replace(start: number, end: number, block: Block) {
    if (TextUtils.isEmpty(this.text) || !block) {
      return;
    }
    if (!this.blockSections) {
      this.blockSections = [];
    }
    if (NumberUtils.between(start, 0, this.text.length) && NumberUtils.between(end, 0, this.text.length)) {
      var section = {start, end, block}
      this.blockSections.push(section);
    } else {
      throw "OutOfBoundException ";
    }
  }

  public build(): Array<Block> {
    var blocks: Array<Block> = [];
    if (!this.blockSections || this.blockSections.length == 0) {
      // build all to text
      this.pushTextBlock(blocks, 0, this.text.length);
    } else {
      this.blockSections.sort((section1: BlockSection, section2: BlockSection) => {
        return section1.start - section2.start;
      })
      var endIndex = 0;
      for (let index = 0; index < this.blockSections.length; index++) {
        const section = this.blockSections[index];
        if (section.start != endIndex) {
          // build text
          this.pushTextBlock(blocks, endIndex, section.start);
        }
        blocks.push(section.block);
        endIndex = section.end;
      }
      // build text
      if (endIndex < this.text.length) {
        this.pushTextBlock(blocks, endIndex, this.text.length);
      }
    }
    return blocks;
  }

  private pushTextBlock(blocks: Array<Block>, start: number, end: number) {
    var content = this.text.substring(start, end);
    content.split(this.separator).forEach((text) => {
      // 区分英语、语文
      const textBlock = BlockProvider.getInstance().getBlockMaker().buildTextBlock(text);
      blocks.push(textBlock);
    });
  }
}

// 代码块
interface BlockSection {
  start: number;
  end: number;
  block: Block;
}
